package cn.com.ejiakanghu.service;

import cn.com.ejiakanghu.annotation.LoginUser;
import cn.com.ejiakanghu.config.LocationContext;
import cn.com.ejiakanghu.core.config.DirectExchangeRabbitMQConfig;
import cn.com.ejiakanghu.core.exceptions.BizException;
import cn.com.ejiakanghu.core.rabbitmq.DirectExchangeProducer;
import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.dto.*;
import cn.com.ejiakanghu.vo.*;
import cn.com.ejiakanghu.vo.UserVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.divided.AgedmallInfoPromoteUserSettlementMapper;
import org.linlinjava.litemall.db.dao.divided.AgedmallPromoteUserWithdrawalRecordMapper;
import org.linlinjava.litemall.db.dao.divided.LitemallGoodsPromoteSpecificationMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.jsonfield.LitemallGoodsProductSpecification;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.AgedmallCashoutConstant;
import org.linlinjava.litemall.db.util.AgentConstant;
import org.linlinjava.litemall.db.util.AgentSettleDetailConstant;
import org.linlinjava.litemall.db.util.OrderGoodsConstant;
import org.linlinjava.litemall.db.vo.app.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class UserManager {
    @Autowired
    private LitemallUserService litemallUserService;
    @Autowired
    private AgedmallUserInfoService agedmallUserInfoService;
    @Autowired
    private AgedmallAgentService agedmallAgentService;
    @Autowired
    private AgedmallDeductDetailService agedmallDeductDetailService;
    @Autowired
    private LitemallGoodsService litemallGoodsService;
    @Autowired
    private AgedmallGoodsDeductionConfService agedmallGoodsDeductionConfService;
    @Autowired
    private AgedmallAgentSettleDetailService agedmallAgentSettleDetailService;
    @Autowired
    private LitemallOrderService litemallOrderService;
    @Autowired
    private AgedmallHospitalSendService agedmallHospitalSendService;
    @Autowired
    private AgedmallInfoPromoteUserSettlementService infoPromoteUserSettlementService;
    @Autowired
    private AgedmallPromoteUserSettlementService userSettlementService;

    @Resource
    private LitemallGoodsMapper litemallGoodsMapper;

    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;

    @Resource
    private AgedmallServiceOrderMapper agedmallServiceOrderMapper;
    @Resource
    private LitemallGoodsProductMapper litemallGoodsProductMapper;
   @Resource
    private AgedmallPromoteWithdrawalRecordMapper agedmallPromoteWithdrawalRecordMapper;

    @Resource
    private AgedmallPromoteUserWithdrawalRecordMapper agedmallPromoteUserWithdrawalRecordMapper;

    @Resource
    private LitemallGoodsPromoteSpecificationMapper litemallGoodsPromoteSpecificationMapper;

    @Resource
    private AgedmallInfoPromoteUserSettlementMapper agedmallInfoPromoteUserSettlementMapper;

    @Resource
    private AgedmallOnlineServiceMapper  agedmallOnlineServiceMapper;

    @Resource
    private AgedmallUserInfoMapper agedmallUserInfoMapper;

    @Resource
    private DirectExchangeProducer directExchangeProducer;
    @Autowired
    private AgedmallBusinessInfoService agedmallBusinessInfoService;
    @Resource
    private AgedmallVipLevelMapper agedmallVipLevelMapper;

    @Resource
    private LitemallOrderItemMapper litemallOrderItemMapper;

    @Resource
    private CartManager cartManager;



    public BaseResult getUserInfo(Integer userId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        LitemallUser litemallUser = litemallUserService.findById(userId);
        AgedmallUserInfo agedmallUserInfo = agedmallUserInfoService.getByUid(userId);
        if (null == agedmallUserInfo) {
            agedmallUserInfo = new AgedmallUserInfo();
            agedmallUserInfo.setUserId(userId);
            agedmallUserInfo.setAgentAmount(BigDecimal.ZERO);
            agedmallUserInfo.setDeductAmount(BigDecimal.ZERO);
            agedmallUserInfoService.add(userId);
        }
        UserRoleData roleData = getUserRoles(userId);
        List<AgedmallAgent> agentList = roleData.getAgentList();
        String rolesStr = roleData.getRoles();
        UserInfoVo userInfoVo = UserInfoVo.getInstance(litemallUser, rolesStr);
        AgedmallVipLevel vipLevel = agedmallVipLevelMapper.selectByPrimaryKey(litemallUser.getUserLevel().intValue());
        userInfoVo.setVipLevel(vipLevel!=null?vipLevel.getVipLevel():0);
        UserVo userVo = new UserVo();
        userVo.setUserInfo(userInfoVo);
        userVo.setCouponCount(0);
        userVo.setDeductCount(agedmallUserInfo.getDeductAmount());
        userVo.setBalanceMoney(agedmallUserInfo.getAgentAmount());
        Long storeId = agentList.stream().filter(p -> p.getType() == AgentConstant.TYPE_STORE).map(p -> p.getStoreId()).findFirst().orElse(null);
        userVo.setStoreId(null == storeId ? null : storeId.intValue());
        return RespUtil.success(userVo);
    }

    /**
     * 获取用户角色信息
     * @param userId
     * @return
     */
    public UserRoleData getUserRoles(int userId) {
        List<String> roleList = new ArrayList<>();
        roleList.add("user");
        List<AgedmallAgent> agentList = agedmallAgentService.getByUid(userId);
        List<Byte> agentTypeList = agentList.stream().map(AgedmallAgent::getType).distinct().collect(Collectors.toList());
        for(Byte t:agentTypeList) {
            switch (t) {
                case 1:
                    //1普通代理
                    roleList.add("saleman");
                    break;
                case 2:
                    //2医生代理
                    roleList.add("hosguider");
                    break;
                case 3:
                    //3药店 TODO
                    break;
            }
        }

        //是否为代理店铺
        int countBusi = agedmallBusinessInfoService.isExistsBusiAdmin(userId);
        if(countBusi > 0) {
            roleList.add("store");
        }

        List<String> deliveryRoles = agedmallAgentService.getDeliveryRoles(userId);
        roleList.addAll(deliveryRoles);
        String rolesStr = StringUtils.join(roleList,",");
        UserRoleData roleData = new UserRoleData();
        roleData.setRoles(rolesStr);
        roleData.setDeliveryRoles(deliveryRoles);
        roleData.setAgentList(agentList);
        return roleData;
    }

    /**
     * 个人中心-代理用户-收支明细-获取收支明细数据
     * @param userId
     * @param year
     * @return
     */
    public BaseResult financeDetail(Integer userId, Integer year) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        //统计每个人每天的收入
     /*   List<PromoteCashDto> incomeCountYearList =
                promoteUserWithdrawalRecordMapper.getIncomeCountYearMonth(userId,year);

        List<PromoteCashDto> getWithdrawalYear =
                promoteUserWithdrawalRecordMapper.getWithdrawalYearMonth(userId,year);

        for(PromoteCashDto pc : incomeCountYearList){
            System.err.println("收入:"+pc.getMoney()+ "总笔数:"+pc.getTotal());
            for(PromoteCashDto pcd : getWithdrawalYear){
                if(pc.getYear() == pcd.getYear() && pc.getMoney() == pcd.getMoney()){
                    FinanceDetailMonthVo financeDetailMonthVo = new FinanceDetailMonthVo();
                    financeDetailMonthVo.setYear(pc.getYear().toString());
                    financeDetailMonthVo.setMonth(pc.getMonth().toString());
                    financeDetailMonthVo.setIncomePrice(pc.getMoney());
                    financeDetailMonthVo.setIncomeCount(pc.getTotal());
                    financeDetailMonthVo.setCashOutPrice(pcd.getMoney());
                    financeDetailMonthVo.setIncomeCount(pcd.getTotal());
                }else{

                }
            }
        }*/

        //根据用户id查询提现在信息
       /* List<PromoteCashDto> promoteCashDtoList = promoteUserWithdrawalRecordMapper.getWithdrawal(userId, year);
        List<FinanceDetailMonthVo> financeDetailMonthVoList = new ArrayList<>();
        for(PromoteCashDto bd : promoteCashDtoList){
            //根据年份和月份查询收入信息
            PromoteCashDto cashDto = promoteUserWithdrawalRecordMapper.getIncome(userId,bd.getYear(),bd.getMonth());
            FinanceDetailMonthVo financeDetailMonthVo = new FinanceDetailMonthVo();
            financeDetailMonthVo.setYear(bd.getYear().toString());
            financeDetailMonthVo.setMonth(bd.getMonth().toString());
            financeDetailMonthVo.setCashOutPrice(bd.getMoney());
            //查询提现总笔数
            Integer withdrawalCount = promoteUserWithdrawalRecordMapper.getWithdrawalCount(userId,bd.getYear(),bd.getMonth());
            financeDetailMonthVo.setCashOutCount(withdrawalCount);
            financeDetailMonthVo.setIncomePrice(cashDto.getMoney());
            Integer getIncomeCount = promoteUserWithdrawalRecordMapper.getIncomeCount(userId,bd.getYear(),bd.getMonth());
            financeDetailMonthVo.setIncomeCount(getIncomeCount);

            //查询提现每天的总数
            List<PromoteCashDto> promoteCashDtoListDay = promoteUserWithdrawalRecordMapper.getWithdrawalDay(userId,bd.getYear(),bd.getMonth());
            List<FinanceDetailDayVo> financeDetailDayVoList = new ArrayList<>();
            for(PromoteCashDto pc : promoteCashDtoListDay){
                FinanceDetailDayVo financeDetailDayVo = new FinanceDetailDayVo();
                financeDetailDayVo.setCashOutPrice(pc.getMoney());
                financeDetailDayVo.setDay(pc.getDay().toString());
                Integer withdrawalDayCount = promoteUserWithdrawalRecordMapper
                                 .getWithdrawalDayCount(userId,pc.getYear(),pc.getMonth(),pc.getDay());
                financeDetailDayVo.setCashOutCount(withdrawalDayCount);
                financeDetailDayVoList.add(financeDetailDayVo);

                //根据提现天数查询收入信息
                PromoteCashDto promoteCashDtoDay =
                        promoteUserWithdrawalRecordMapper.getIncomeCountDay(userId,pc.getYear(),pc.getMonth(),pc.getDay());
                if(promoteCashDtoDay !=null){
                    financeDetailDayVo.setIncomePrice(promoteCashDtoDay.getMoney());
                }else{
                    financeDetailDayVo.setIncomePrice(new BigDecimal(0.00));
                }

                Integer promoteCashDtoDayCount =
                        promoteUserWithdrawalRecordMapper.getIncomeCountDayCount(userId,pc.getYear(),pc.getMonth(),pc.getDay());
                if(promoteCashDtoDayCount != null){
                  financeDetailDayVo.setIncomeCount(promoteCashDtoDayCount);
                }else{
                    financeDetailDayVo.setIncomeCount(0);
                }
            }
            financeDetailMonthVo.setDayList(financeDetailDayVoList);
            financeDetailMonthVoList.add(financeDetailMonthVo);

        }*/
        List<FinanceDetailMonthVo> monthVos = agedmallAgentService.getFinanceDetailMonthVo(userId, year);
        for (FinanceDetailMonthVo monthVo : monthVos) {
            List<FinanceDetailDayVo> dayVos = agedmallAgentService.getFinanceDetailDayVo(userId, year, Integer.parseInt(monthVo.getMonth()));
            monthVo.setDayList(dayVos);
        }
        return RespUtil.success(monthVos);
    }

    public BaseResult deductDetailList(Integer userId, Integer page, Integer limit) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        List<DeductDetailListVo> deductDetailListVos = agedmallDeductDetailService.list(userId, page, limit);
        PageInfo<DeductDetailListVo> pagedList = PageInfo.of(deductDetailListVos);

        PageData<DeductDetailListVo> pageData = new PageData<>();
        pageData.setNowPage(page);
        pageData.setTotalPage(pagedList.getPages());
        pageData.setTotalRows((int) pagedList.getTotal());
        pageData.setRows(deductDetailListVos);
        return RespUtil.success(pageData);
    }

    public BaseResult deductGoodsList(Integer userId, Integer page, Integer limit) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        AgedmallUserInfo agedmallUserInfo = agedmallUserInfoService.getByUid(userId);
        if (null == agedmallUserInfo) {
            return RespUtil.badArgumentValue();
        }

        Location location = LocationContext.get();
//        List<LitemallGoods> goodsList = litemallGoodsService.queryDeductList(location.getProvince(), location.getCity(), page, limit);
        List<StoreGoodsVo> goodsList = litemallGoodsService.queryCustomList(location.getProvince(), location.getCity(), page, limit);
        PageInfo<StoreGoodsVo> pagedList = PageInfo.of(goodsList);
        List<GoodsBaseData> goodsBaseDataList = goodsList.stream()
                .map(p -> {
                    // 是否支持医院小时达
                    List<AgedmallHospitalSend> hospitalSends = agedmallHospitalSendService.getByStoreAndGoods(p.getStoreId(), p.getId());
                    p.setIsHospital(hospitalSends.size() > 0 ? 1 : 0);
                    GoodsBaseData goodsBaseData = GoodsBaseData.getInstance(p);
                    // 抵扣金
                    BigDecimal deductNum = agedmallGoodsDeductionConfService.getDeductNumByGoods(p);
                    if (null != deductNum) {
                        goodsBaseData.setDeductNum(deductNum.doubleValue());
                    }
                    return goodsBaseData;
                }).collect(Collectors.toList());

        JSONObject object = new JSONObject();
        object.put("nowPage", page);
        object.put("totalPage", pagedList.getPages());
        object.put("totalRows", (int) pagedList.getTotal());
        object.put("rows", goodsBaseDataList);
        object.put("deductCount", agedmallUserInfo.getDeductAmount());
        return RespUtil.success(object);
    }

    public BaseResult preCashout(Integer userId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        AgedmallUserInfo agedmallUserInfo = agedmallUserInfoService.getByUid(userId);
        if (null == agedmallUserInfo) {
            return RespUtil.badArgumentValue();
        }
        List<UserCashoutBankDto> cashoutBankDtoList = JSONObject.parseArray(agedmallUserInfo.getBankInfo(), UserCashoutBankDto.class);

        JSONObject object = new JSONObject();
        object.put("money", agedmallUserInfo.getAgentAmount());
        object.put("bankcards", cashoutBankDtoList);
        return RespUtil.success(object);
    }

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional
    public synchronized BaseResult cashoutSubmit(Integer userId, BigDecimal money, String channel, Long bankCardId) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        if (AgedmallCashoutConstant.CHANNEL_BANK.equals(channel) && null == bankCardId) {
            return RespUtil.badArgumentValue();
        }
        AgedmallUserInfo agedmallUserInfo = agedmallUserInfoService.getByUid(userId);
        if (null == agedmallUserInfo) {
            return RespUtil.badArgumentValue();
        }
        if (agedmallUserInfo.getAgentAmount().compareTo(money) < 0) {
            throw new BizException("余额不足");
        }
      try {

          AgedmallUserInfo userInfo = this.withdrawalSumMoney(userId);


          agedmallUserInfoService.subtractAgentAmount(userId, money);
          AgedmallPromoteWithdrawalRecord withdrawalRecord = new AgedmallPromoteWithdrawalRecord();
          withdrawalRecord.setUserId(userId);
          withdrawalRecord.setWithdrawalNumber(this.getWithdrawalsNumber());
          withdrawalRecord.setMoney(money);
          withdrawalRecord.setWithdrawalType(channel);
          withdrawalRecord.setWithdrawalTime(LocalDateTime.now());
          withdrawalRecord.setAddTime(LocalDateTime.now());
          withdrawalRecord.setWithdrawalStatus(AgedmallCashoutConstant.STATUS_WATTING);
          withdrawalRecord.setBankcardid(null == bankCardId ? null : bankCardId+"");
          //将记录添加到提现表中，待微信支付成功以后，将状态修改为提现成功或失败状态
         Integer insertNum = agedmallPromoteWithdrawalRecordMapper.insert(withdrawalRecord);
         if(insertNum != 0){
             //发送到MQ中(提现用户userId、提现金额money、申请提现前总金额、申请提现后总金额、提现编号)
             Map<String,Object> withdrawaMap = new HashMap<>();
             withdrawaMap.put("userId",userId);//提现用户id
             withdrawaMap.put("withdrawalNumber",this.getWithdrawalsNumber());//提现编号
             withdrawaMap.put("withdrawalMoney",money);//提现金额
             withdrawaMap.put("withdrawalBeforeMoney",userInfo.getAgentAmount());//申请提现前总金额为
             userInfo = this.withdrawalSumMoney(userId);
             withdrawaMap.put("withdrawalafterMoney",userInfo.getAgentAmount());//申请提现后总金额为

            try {
                rabbitTemplate.convertAndSend(DirectExchangeRabbitMQConfig.DIRECT_EXCANGE_NAME, DirectExchangeRabbitMQConfig.USER_WX_DIRECTROUTING, JacksonUtil.toJson(withdrawaMap));
            }catch (Exception e){
                e.printStackTrace();
            }

         }
          //增加到收支明细表中
           /* AgedmallAgentFinanceDetail agentFinanceDetail = new AgedmallAgentFinanceDetail();
            agentFinanceDetail.setUserId(userId);
            agentFinanceDetail.setType(Byte.parseByte("2"));//收入
            agentFinanceDetail.setAmount(apus.getCommission());
            agentFinanceDetail.setAddTime(LocalDateTime.now());
            agedmallAgentFinanceDetailMapper.insert(agentFinanceDetail);*/
          return RespUtil.success();
      }catch (Exception e){
          return RespUtil.fail();
      }
    }


    /**
     * 获取账号总金额
     * @return
     */
    private AgedmallUserInfo withdrawalSumMoney(Integer userId){
        //查询提现前总金额
        AgedmallUserInfoExample userInfoExample = new AgedmallUserInfoExample();
        userInfoExample.or().andUserIdEqualTo(userId);
        AgedmallUserInfo userInfo = agedmallUserInfoMapper.selectOneByExample(userInfoExample);
        return userInfo;
    }


    private String getWithdrawalsNumber() {
        // 时间戳加自增数据库6位id
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        int number = add();
        return time + StringUtils.leftPad(number + "", 6, "0");
    }


    public int add(){
        //取出最新一条数据的id
        Integer lastId = agedmallPromoteUserWithdrawalRecordMapper.getUserWithdrawarLast();
        if(lastId == null){
            return 0;
        }else {
            return lastId;
        }
    }


    /**
     * 查询提现记录
     * @param userId
     * @param page
     * @param limit
     * @return
     */
    public BaseResult cashoutDetail(Integer userId, Integer page, Integer limit) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        AgedmallUserInfo agedmallUserInfo = agedmallUserInfoService.getByUid(userId);
        if (null == agedmallUserInfo) {
            return RespUtil.badArgumentValue();
        }
        List<UserCashoutBankDto> cashoutBankDtoList = new ArrayList<>();
        if (StringUtils.isNotEmpty(agedmallUserInfo.getBankInfo())) {
            cashoutBankDtoList = JSONObject.parseArray(agedmallUserInfo.getBankInfo(), UserCashoutBankDto.class);
        }
        Map<String, UserCashoutBankDto> bankMap = cashoutBankDtoList.stream().collect(Collectors.toMap(p->p.getId()+"", p->p, (p1,p2) -> p2));
        List<AgedmallPromoteWithdrawalRecord> detailList = infoPromoteUserSettlementService.list(userId, page, limit);
        List<CashoutDetailListVo> cashoutDetailListVos = detailList.stream()
                .map(p -> new CashoutDetailListVo(p, bankMap.get(p.getBankcardid()))).collect(Collectors.toList());
        int total = infoPromoteUserSettlementService.listCount(userId);
        int pages = total % limit == 0 ? total / limit : total / limit + 1;
        PageData<CashoutDetailListVo> pageData = new PageData<>();
        if (detailList.size() == 0) {
            return RespUtil.success(pageData);
        }
        pageData.setNowPage(page);
        pageData.setTotalPage(pages);
        pageData.setTotalRows(total);
        pageData.setRows(cashoutDetailListVos);
        return RespUtil.success(pageData);
    }

    /**
     * 查询提现信息
     * @param page
     * @param pageSize
     * @return
     */
    public BaseResult getWithdrawalRecodrInfo(Integer page, Integer pageSize){
        List<AgedmallPromoteWithdrawalRecord> withdrawalRecordList = userSettlementService.getWithdrawalRecodrInfo(page,pageSize);
        PageInfo<AgedmallPromoteWithdrawalRecord> pagedList = PageInfo.of(withdrawalRecordList);
        PageData<AgedmallPromoteWithdrawalRecord> pageData = new PageData<>();
        pageData.setNowPage(page);
        pageData.setTotalPage(pagedList.getPages());
        pageData.setTotalRows((int) pagedList.getTotal());
        pageData.setRows(withdrawalRecordList);
        return RespUtil.success(pageData);
    }

    /**
     * 个人中心-代理用户-分成订单-获取分成订单列表数据
     * @param userId
     * @param keyword
     * @param proxyStatus
     * @param subOrderType
     * @param year
     * @param month
     * @param page
     * @param pageSize
     * @return
     */
    public BaseResult settleOrderList(Integer userId, String keyword, Integer proxyStatus, String subOrderType, String year, String month, Integer page, Integer pageSize) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        DiviedQuery diviedQuery = new DiviedQuery();
        diviedQuery.setUserId(userId);
        diviedQuery.setProxyStatus(proxyStatus);
        diviedQuery.setSubOrderType(subOrderType);
        diviedQuery.setPage(page);
        diviedQuery.setPageSize(pageSize);
        diviedQuery.setYear(year);
        diviedQuery.setMonth(month);
        List<AgedmallPromoteUserSettlementDto> promoteUserSettlementList = userSettlementService.getPromoteUserSettleMent(diviedQuery);
        List<AppAgentSettleDetail> appAgentSettleDetails = new ArrayList<>();
        for(AgedmallPromoteUserSettlementDto aps : promoteUserSettlementList){
            AppAgentSettleDetail appAgentSettleDetail = new AppAgentSettleDetail();
            appAgentSettleDetail.setBigOrderId(aps.getBigNumber());
            appAgentSettleDetail.setSubOrderId(aps.getSmallNumber());
            appAgentSettleDetail.setSubOrderType(aps.getGoodsType());
             //getOrderSumMoney
            OrderSumMoneryDto orderSumMoneryDto = userSettlementService.getOrderSumMoney(aps.getSmallNumber());
            //子订单总金额
            appAgentSettleDetail.setSubOrderPrice(orderSumMoneryDto.getOrderPrice().add(orderSumMoneryDto.getServicePrice()==null ? BigDecimal.ZERO : orderSumMoneryDto.getServicePrice()));
            appAgentSettleDetail.setProxyStatus(aps.getStatus());
            BigDecimal promoteSumMoney = agedmallInfoPromoteUserSettlementMapper.getpromoteSumMoney(aps.getSettlementId());
            appAgentSettleDetail.setProxyPrice(promoteSumMoney);
            appAgentSettleDetail.setProxyTime(aps.getWithdrwalTime());
            appAgentSettleDetails.add(appAgentSettleDetail);
            LitemallOrder order = litemallOrderService.findBySn(aps.getBigNumber());
            List<LitemallOrderGoods> orderGoodsList = agedmallAgentSettleDetailService.getSettleOrderGoods(order.getId(), null);
            // 商品列表
            List<LitemallOrderGoods> orderGoodsGoodsList = orderGoodsList.stream().filter(p -> OrderGoodsConstant.TYPE_GOODS.endsWith(p.getType())).collect(Collectors.toList());
            // 配件列表
           // List<LitemallOrderGoods> partsList = orderGoodsList.stream().filter(p -> OrderGoodsConstant.TYPE_CUSTOM.endsWith(p.getType())).collect(Collectors.toList());
            List<DividedGoods> goodsList = this.getOrderGoods(orderGoodsGoodsList);
            appAgentSettleDetail.setGoodsList(goodsList);
        }
        //List<AppAgentSettleDetail> settleDetails = agedmallAgentSettleDetailService.list(userId, keyword, proxyStatus, subOrderType, year, month, page, pageSize);
        PageInfo<AppAgentSettleDetail> pagedList = PageInfo.of(appAgentSettleDetails);
     /*   List<SettleOrderListVo> settleOrderListVos = settleDetails.stream()
                .map(p -> {
                    LitemallOrder bigOrder = null; //litemallOrderService.findBySn(p.getBigOrderSn());
                    //LitemallOrder order = litemallOrderService.findBySn(p.getSubOrderSn());
                    List<LitemallOrderGoods> orderGoodsList = agedmallAgentSettleDetailService.getSettleOrderGoods(order.getId(), p.getProxyStatus().intValue());
                    List<SubOrderGoodsVo> subOrderGoodsList = orderManager.getGoodsList(orderGoodsList);

                    SettleOrderListVo settleOrderListVo = SettleOrderListVo.getInstance(p, bigOrder, order, subOrderGoodsList);
                    return settleOrderListVo;
                }).collect(Collectors.toList());*/
        PageData<AppAgentSettleDetail> pageData = new PageData<>();
        pageData.setNowPage(page);
        pageData.setTotalPage(pagedList.getPages());
        pageData.setTotalRows((int) pagedList.getTotal());
        pageData.setRows(appAgentSettleDetails);
        return RespUtil.success(pageData);
    }

    private List<DividedGoods> getOrderGoods(List<LitemallOrderGoods> orderGoodsGoodsList){
        List<DividedGoods> goodsList = new ArrayList<>();
        for(LitemallOrderGoods log : orderGoodsGoodsList){
           DividedGoods dividedGoods =  this.getdividedGoodsList(log);
           //查询规格名称
          List<GoodsSpecInfoDto> goodsSpecInfoDtoList =
                    litemallGoodsPromoteSpecificationMapper.getAdditionalInfo(OrderGoodsConstant.TYPE_CUSTOM,log.getGoodsId());
          if(!goodsSpecInfoDtoList.isEmpty()){
              List<DiviedCustom> customList = new ArrayList<>();
              for(GoodsSpecInfoDto gd : goodsSpecInfoDtoList){
                  DiviedCustom custom = new DiviedCustom();
                  custom.setName(gd.getSpecInfoName());

                 // String orderCode = "20211230172423002107";
                  //String childOrderCode = "20211230172423002107-1";
                  //查询litemall_order_goods
                  LitemallOrderGoodsExample goodsExample = new LitemallOrderGoodsExample();
                  goodsExample.or()
                          .andOrderCodeEqualTo(log.getOrderCode())//orderCode  log.getOrderCode() orderCode
                          .andChildOrderCodeEqualTo(log.getChildOrderCode())//childOrderCode log.getChildOrderCode()  childOrderCode
                          .andSpecInfoIdEqualTo(gd.getSpecInfoId());//gd.specInfoId 999
                  List<LitemallOrderGoods> litemallOrderGoodsList = litemallOrderGoodsMapper.selectByExample(goodsExample);
                  List<DividedGoods> dividedGoodsList = new ArrayList<>();
                  for(LitemallOrderGoods lod : litemallOrderGoodsList){
                      DividedGoods goodsCustome =  this.getdividedGoodsList(lod);
                      dividedGoodsList.add(goodsCustome);
                  }
                  custom.setGoodsList(dividedGoodsList);
                  customList.add(custom);
              }
              dividedGoods.setCustomList(customList);
          }


            List<GoodsSpecInfoDto> goodsServiceInfoDtoList =
                    litemallGoodsPromoteSpecificationMapper.getAdditionalInfo(OrderGoodsConstant.TYPE_ONLINE,log.getGoodsId());//1181397
            if(!goodsServiceInfoDtoList.isEmpty()){
                List<DividedService> serviceList = new ArrayList<>();
                for(GoodsSpecInfoDto  ser : goodsServiceInfoDtoList){
                    DividedService custom = new DividedService();
                    custom.setName(ser.getSpecInfoName());
                    //通过订单编号id到服务订单表中查询
                    AgedmallServiceOrderExample serviceOrderExample = new AgedmallServiceOrderExample();
                    serviceOrderExample.or().andOrderIdEqualTo(log.getOrderId().longValue());//log.getOrderId().longValue() 2709L
                    List<AgedmallServiceOrder> agedmallServiceOrderList = agedmallServiceOrderMapper.selectByExample(serviceOrderExample);
                    List<DividedGoods> dividedGoodsList = new ArrayList<>();
                    for(AgedmallServiceOrder aso : agedmallServiceOrderList){
                        DividedGoods goodsCustome =  this.getdividedGoodsServiceList(aso);
                        dividedGoodsList.add(goodsCustome);
                    }
                    custom.setGoodsList(dividedGoodsList);
                    serviceList.add(custom);
                }
                dividedGoods.setServiceList(serviceList);
            }
            LitemallGoodsProduct goodsProduct=litemallGoodsProductMapper.selectByPrimaryKey(log.getProductId());
            LitemallOrderItem orderItem=litemallOrderItemMapper.selectByPrimaryKey(log.getChildOrderId().intValue());
            LitemallGoods goods=litemallGoodsMapper.selectByPrimaryKey(goodsProduct.getGoodsId());
            GoodsVipSalesDto selectProductVipSale = cartManager.getSelectProductVipSale(goodsProduct.getVipJson(),
                    orderItem.getUserId(),log.getNumber().intValue(),goods.getVipPriceFlag());
            dividedGoods.setSelectedSkuVipSale(selectProductVipSale);

           goodsList.add(dividedGoods);
        }
        return goodsList;
    }

    private DividedGoods getdividedGoodsServiceList(AgedmallServiceOrder log){
        //根据服务id查询服务信息
        AgedmallOnlineService onlineService = agedmallOnlineServiceMapper.selectByPrimaryKey(log.getServiceId());
        DividedGoods dividedGoods = new DividedGoods();
        dividedGoods.setId(onlineService.getId());
        dividedGoods.setName(onlineService.getName());
        String serviceUrls = onlineService.getServiceImage();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(serviceUrls)) {
            List<String> urlList = JSONObject.parseArray(serviceUrls, String.class);
            dividedGoods.setImage(CollectionUtils.isNotEmpty(urlList) ? urlList.get(0) : null);
        }
        dividedGoods.setType("service");
        dividedGoods.setPrice(log.getServicePrice());
        dividedGoods.setBuycount(1);//目前是1个服务
        //查询服务规格信息
        LitemallGoodsProduct goodsProduct = litemallGoodsProductMapper.selectByPrimaryKey(log.getServiceProductId());
        //获取skuName
        if(goodsProduct.getSpecifications() != null){
            List<LitemallGoodsProductSpecification> specifications
                    = JSON.parseArray(goodsProduct.getSpecifications(), LitemallGoodsProductSpecification.class);
            StringBuffer sku = new StringBuffer();
            for(LitemallGoodsProductSpecification lgs : specifications){
                StringBuffer sb = new StringBuffer();
                sb.append(lgs.getInfoName()).append(":").append(lgs.getName());
                sku.append(sb).append(";");
            }
            String spiltSku = sku.substring(0,sku.length()-1);
            dividedGoods.setSkuName(spiltSku);
        }
        return dividedGoods;
    }

    private DividedGoods getdividedGoodsList(LitemallOrderGoods log){
        DividedGoods dividedGoods = new DividedGoods();
        dividedGoods.setId(log.getGoodsId());
        dividedGoods.setName(log.getGoodsName());

        //根据商品id查询商品类型
        LitemallGoods litemallGoods = litemallGoodsMapper.selectByPrimaryKey(log.getGoodsId());
         if(log.getPicUrl() != null){
            dividedGoods.setImage(log.getPicUrl());
        }else{
         //通过商品id查询图片信息
         dividedGoods.setImage(log.getPicUrl());
         }
        dividedGoods.setType(litemallGoods.getGoodsType());
        dividedGoods.setPrice(log.getPrice());
        dividedGoods.setBuycount(log.getNumber().intValue());
        //获取skuName
        if(log.getSpecifications() != null){
            List<LitemallGoodsProductSpecification> specifications
                    = JSON.parseArray(log.getSpecifications(), LitemallGoodsProductSpecification.class);
            StringBuffer sku = new StringBuffer();
            for(LitemallGoodsProductSpecification lgs : specifications){
                StringBuffer sb = new StringBuffer();
                sb.append(lgs.getInfoName()).append(":").append(lgs.getName());
                sku.append(sb).append(";");
            }
            String spiltSku = sku.substring(0,sku.length()-1);
            dividedGoods.setSkuName(spiltSku);
        }
        return dividedGoods;
    }

    /**
     * 分成统计
     * @param userId
     * @param year
     * @return
     */
    public BaseResult settleStatistics(@LoginUser Integer userId, Integer year) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        List<SettleStatisticsVo> settleStatisticsVos = infoPromoteUserSettlementService.getSettleStatisticsVo(userId, year);
        JSONObject object = new JSONObject();
       // String desc = SystemConfig.getLitemallSettleStatisticsDesc();
        object.put("desc", "每月10号结算上月的推广金额,可去提现");
        object.put("monthList", settleStatisticsVos);
        return RespUtil.success(object);
    }

    /**
     * 个人中心-代理用户-分成统计-获取指定年月的结算详情
     * @param userId
     * @param year
     * @param month
     * @return
     */
    public BaseResult settleDetail(@LoginUser Integer userId, Integer year, Integer month) {
        if (userId == null) {
            return RespUtil.unlogin();
        }
        SettleDetailVo settleDetailVo = new SettleDetailVo();
        //本月最终获得分成金额
        List<ProxyMoneyVo> getProxyMoneyVoList = infoPromoteUserSettlementService.getProxyMoneyVoList(userId, year, month, AgentSettleDetailConstant.ITEM_INCOME);
        List<ProxyMoneyVo> proxyMoneyVoList = new ArrayList<>();
        for(ProxyMoneyVo pm : getProxyMoneyVoList ){
            ProxyMoneyVo proxyMoneyVo = new ProxyMoneyVo();
            if(pm.getName().equals("lease")){
                proxyMoneyVo.setName("租赁商品");
            }else if(pm.getName().equals("sale")){
                proxyMoneyVo.setName("销售商品");
            }else if(pm.getName().equals("service")){
                proxyMoneyVo.setName("服务商品");
            }else{
                proxyMoneyVo.setName("未知商品");
            }
            proxyMoneyVo.setPrice(pm.getPrice());
            proxyMoneyVoList.add(proxyMoneyVo);
        }
        BigDecimal proxyPrice = infoPromoteUserSettlementService.getProxyMoneyMontyProxy(userId, year, month);
        settleDetailVo.setProxyPrice(proxyPrice);
        settleDetailVo.setProxyMoneyList(proxyMoneyVoList);

        /*settleDetailVo.setProxyOrderList(agedmallAgentSettleDetailService.getProxyOrderVoList(userId, year, month, AgentSettleDetailConstant.ITEM_INCOME));
        settleDetailVo.setRefundMoneyList(agedmallAgentSettleDetailService.getProxyMoneyVoList(userId, year, month, AgentSettleDetailConstant.ITEM_REFUND));
        settleDetailVo.setRefundOrderList(agedmallAgentSettleDetailService.getProxyOrderVoList(userId, year, month, AgentSettleDetailConstant.ITEM_REFUND));
        settleDetailVo.setPlusMoneyList(agedmallAgentSettleDetailService.getProxyMoneyVoList(userId, year, month, AgentSettleDetailConstant.ITEM_INCREASE));
        settleDetailVo.setSubMoneyList(agedmallAgentSettleDetailService.getProxyMoneyVoList(userId, year, month, AgentSettleDetailConstant.ITEM_DEDUCTION));
*/
        return RespUtil.success(settleDetailVo);
    }
}
